<template>
  <div class="main-page list-page el-card">
    <!-- 头部信息 -->
    <header class="header-box">
      <div class="header-left">
        <div class="header-left-title">
          {{ headerInfo?.sectionName || "-" }}
        </div>
        <div class="header-left-code">
          {{ headerInfo?.sectionCode || "-" }} | 合同金额（不含税)：
          {{ headerInfo.contractAmount || 0 }}元
        </div>
      </div>
      <div class="header-right">
        <div class="header-card scend-card first-card">
          <Fragment>
            <div class="header-card-title">累计预转固金额</div>
            <Fragment>
              <span class="header-card-number">
                {{ formatNumber(headerInfo.preTransferSum || 0) }}
              </span>
              <span class="header-card-unit">元</span>
            </Fragment>
          </Fragment>
          <div class="header-card-line"></div>
          <Fragment>
            <div class="header-card-title">累计预转固比例</div>
            <div class="header-card-progress">
              <span class="header-card-number">
                {{ headerInfo.preTransferRate || 0 }}%
              </span>
              <el-progress
                style="width: 80%"
                :percentage="headerInfo.preTransferRate"
                status="success"
                :show-text="false"
              />
            </div>
          </Fragment>
        </div>
        <div class="header-card scend-card">
          <Fragment>
            <div class="header-card-title">累计正式转固金额</div>
            <Fragment>
              <span class="header-card-number">
                {{ formatNumber(headerInfo.transferSum || 0) }}
              </span>
              <span class="header-card-unit">元</span>
            </Fragment>
          </Fragment>
          <div class="header-card-line"></div>
          <Fragment>
            <div class="header-card-title">累计正式转固比例</div>
            <div class="header-card-progress">
              <span class="header-card-number">
                {{ headerInfo.transferRate || 0 }}%
              </span>
              <el-progress
                style="width: 80%"
                :percentage="headerInfo.transferRate || 0"
                status="success"
                :show-text="false"
              />
            </div>
          </Fragment>
        </div>
      </div>
    </header>
    <!-- 操作区域 -->
    <div class="action-box">
      <el-button type="primary" @click="handleEditClick()">
        <el-icon class="icon-plus"><Plus /></el-icon>新增
      </el-button>
      <el-button type="primary" @click="showImport = true">
        <el-icon class="icon-plus"><Upload /></el-icon>导入
      </el-button>
      <el-button type="primary" @click="handleExport">
        <el-icon class="icon-plus"><Download /></el-icon>导出
      </el-button>
    </div>
    <!-- 表格区域 -->
    <div
      class="content"
      :style="{
        height: `calc(100% - ${contentHight + 52}px)`
      }"
    >
      <PageContent
        :contentTableConfig="contentTableConfig"
        :searchFn="getDataList"
        :queryParams="queryParams"
        ref="pageContentRef"
      >
        <template #paymentAmount="scope">
          <span>
            {{ formatNumber(scope.row.paymentAmount) }}
          </span>
        </template>
        <template #isTransfer="scope">
          <span>
            {{ scope.row.isTransfer === "1" ? "正式转固" : "预转固" }}
          </span>
        </template>
        <template #handler="scope">
          <div class="handle-btns">
            <el-button type="text" link @click="handleEditClick(scope.row)">
              编辑
            </el-button>
            <el-popconfirm
              confirm-button-text="确定"
              cancel-button-text="取消"
              icon="el-icon-info"
              icon-color="red"
              title="确定删除？"
              @confirm="handleDeleteClick(scope.row)"
            >
              <template #reference>
                <el-button
                  type="text"
                  class="btns-danger"
                  v-auth="`/projects/template--delete`"
                  >删除</el-button
                >
              </template>
            </el-popconfirm>
          </div>
        </template>
      </PageContent>
    </div>
    <PageModal
      ref="pageModalRef"
      :width="'30%'"
      :modalConfig="modalConfig"
      :title="isEdit ? '编辑合同转固' : '新增合同转固'"
      @submitData="submitData"
      :btn-loading="btnLoading"
      :default-info="detailInfo"
    >
      <template #uploadSlot>
        <span>支持自定义上传组件</span>
      </template>
    </PageModal>
    <import-dom
      v-if="showImport"
      ref="importRef"
      @cancel="showImport = false"
      @submit="submitImport"
      :title="'批量导入合同转固'"
      :fileName="'转固导入模板.xlsx'"
    ></import-dom>
  </div>
</template>

<script setup lang="ts">
import {
  getPaymentTransfer,
  getDataList,
  addData,
  updateData,
  deleteData,
  importData
} from "/@/api/contractPayment";
import importDom from "/@/components/import/import.vue";
import { formatNumber } from "/@/utils/formatNumber.ts";
import PageContent from "/@/components/page-content/index.vue";
import PageModal from "/@/components/page-modal/index.vue";
import { contentTableConfig } from "./config/content.config.ts";
import { modalConfig } from "./config/modal.config.ts";
import { computed, ref, onMounted } from "vue";
import { exportExcel } from "/@/utils/file";
import { storageLocal } from "/@/utils/storage";
import { useHeight } from "/@/hooks/use-height";
import NotifMessage from "/@/utils/message/notification";
import dayjs from "dayjs";
// 导入
const showImport = ref(false);

const sectionId = storageLocal.getItem("sectionInfo")?.id ?? "";
const projectManageId = storageLocal.getItem("projectInfo")?.id ?? "";

onMounted(async () => {
  getHeaderInfo();
});

// 表格组件
const pageContentRef = ref<InstanceType<typeof PageContent>>();

// 模态框组件
const pageModalRef = ref<InstanceType<typeof PageModal>>();

// 查询参数
const queryParams = ref({
  sectionId,
  secType: "1",
  projectManageId
});

// 导入
const importRef = ref<HTMLFormElement | null>(null) as any;
const submitImport = async formData => {
  try {
    formData.append("sectionId", queryParams.value.sectionId);
    formData.append("secType", queryParams.value.secType);
    formData.append("projectManageId", queryParams.value.projectManageId);
    const { code, message } = await importData(formData);
    if (code === 200) {
      NotifMessage.success(message);
      showImport.value = false;
      queryClick();
      getHeaderInfo();
    } else {
      NotifMessage.error(message || "请重试");
    }
  } catch (err) {
    importRef.value.handleRemove();
  }
};

const queryClick = () => {
  pageContentRef.value?.queryTableData(queryParams.value);
};

// 获取头部信息
const headerInfo = ref({});
const getHeaderInfo = async () => {
  try {
    const { data } = await getPaymentTransfer(queryParams.value);
    headerInfo.value = data;
  } catch (error) {
    console.log(error);
  }
};

// 编辑/新增事件
const isEdit = ref(false);
const detailInfo = ref({});
const handleEditClick = (item?: any) => {
  isEdit.value = !!item;
  if (item) {
    detailInfo.value = {
      paymentTime: item.paymentTime,
      paymentAmount: item.paymentAmount,
      isTransfer: item.isTransfer,
      note: item.note,
      id: item.id
    };
  }
  pageModalRef.value?.openModal();
};

// 删除事件
const handleDeleteClick = async (item: any) => {
  try {
    const { data } = await deleteData(item.id);
    if (data) {
      NotifMessage.success("删除成功");
      pageContentRef.value?.queryTableData(queryParams.value);
      getHeaderInfo();
    }
  } catch (error) {
    console.log(error);
  }
};

// 导出数据
const handleExport = () => {
  let formData = {
    ...queryParams.value
  };
  const name = `${storageLocal.getItem("sectionInfo")?.name}_合同转固`;
  exportExcel("/snow-admin/paymentTransfer/exportBatch", formData, name);
};

// 提交事件
const btnLoading = ref(false);
const submitData = async (payload: any) => {
  btnLoading.value = true;
  try {
    const params = {
      ...queryParams.value,
      ...payload.value,
      paymentTime: payload.value.paymentTime
        ? dayjs(payload.value.paymentTime).format("YYYY-MM-DD")
        : ""
    };
    let res;
    if (isEdit.value) {
      params.id = detailInfo.value.id;
      const { data } = await updateData(params);
      res = data;
    } else {
      const { data } = await addData(params);
      res = data;
    }
    if (res) {
      NotifMessage.success(isEdit.value ? "修改成功" : "新增成功");
      pageModalRef.value?.closeModal();
      pageContentRef.value?.queryTableData(queryParams.value);
      getHeaderInfo();
    }
  } catch (error) {
    console.log(error);
  } finally {
    btnLoading.value = false;
  }
};

const contentHight = computed(() => useHeight());
</script>
<style scoped lang="scss">
.main-page {
  position: relative;
  width: 100%;
  height: 100%;

  .header-box {
    padding: 16px 20px;
    border-bottom: 1px solid #f2f3f6;
    display: flex;
    justify-content: space-between;
    .header-left {
      &-title {
        font-size: 22px;
        font-family: PingFangSC-Medium, PingFang SC;
        font-weight: 600;
        color: #333333;
        line-height: 30px;
      }
      &-code {
        font-size: 16px;
        color: #999999;
        margin-top: 4px;
      }
    }

    .header-right {
      display: flex;
    }

    .header-card {
      width: 320px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      border: 0px solid #0073e5;
      padding: 15px 16px;
      border-radius: 8px;
      margin-right: 16px;

      &-title,
      &-unit {
        font-size: 14px;
        font-weight: 500;
        line-height: 22px;
        color: #333333;
      }

      &-number {
        font-size: 18px;
        font-weight: 600;
        line-height: 32px;
        color: #333333;
        margin-right: 4px;
      }

      &-line {
        width: 1px;
        height: 44px;
        background: #d6e2df;
      }

      &-progress {
        display: flex;
        width: 120px;
      }
    }

    .scend-card {
      background: linear-gradient(
        105deg,
        #def3ee 6%,
        rgba(226, 250, 245, 0.41) 55%,
        #def3ee 99%
      );
    }
    .first-card {
      background: linear-gradient(
        115deg,
        #edf4ff 3%,
        rgba(242, 247, 253, 0.73) 53%,
        #edf4ff 100%
      );
    }
  }

  .action-box {
    margin-top: 10px;
    padding-left: 20px;
  }

  .content {
    padding: 0 20px;
  }

  .page-search {
    padding: 0;
  }
}
</style>
